package com.yx.louti.authCode.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import cn.hutool.log.Log;
import com.yx.louti.authCode.model.ImgAuthCode;
import com.yx.louti.globalException.model.BizAssert;
import jtool.JString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 验证码,图形验证码service
 */
@Service
public class AuthCodeService {
    @Autowired
    RedisTemplate<String, String> redisTemplate;


    /**
     * 创建图形验证码
     *
     * @return 图形验证码
     */
    public ImgAuthCode createImgAuthCode() {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 150, 4, 0);
        String imageBase64 = lineCaptcha.getImageBase64();
        String code = lineCaptcha.getCode();

        ImgAuthCode authCode = new ImgAuthCode(UUID.fastUUID().toString(true), imageBase64, code);
        //保存到redis
        redisTemplate.opsForValue().set("lt-authCode-" + authCode.getId(), authCode.getCode(), 5 * 60, TimeUnit.SECONDS);
        Log.get().info("验证码的key:{}","lt-authCode-" + authCode.getId());
        return authCode;
    }

    /**
     * 验证验证码
     *
     * @param authCodeId 验证码id
     * @param code       验证码
     * @return
     */
    public boolean verifyAuthCode(String authCodeId, String code) {
        return verifyAuthCode(authCodeId, code, false);
    }

    /**
     * 验证验证码
     *
     * @param authCodeId 验证码id
     * @param code       验证码
     * @param sms        是否是短信验证码
     * @return
     */
    public boolean verifyAuthCode(String authCodeId, String code, boolean sms) {
        BizAssert.notEmpty(authCodeId);
        BizAssert.notEmpty(code);
        String cc = redisTemplate.opsForValue().get("lt-authCode-" + authCodeId);
        //图形验证码只能校验一次, 校验玩即删除,短信验证码不删除,可以重复尝试验证
        if (!sms && JString.isNotEmpty(cc))
            removeAuthCode(authCodeId);
        if (cc == null) {
            return false;
        }
        return code.trim().equalsIgnoreCase(cc.trim());
    }

    /**
     * 删除验证码
     *
     * @param authCodeId
     */
    public void removeAuthCode(String authCodeId) {
        redisTemplate.delete("lt-authCode-" + authCodeId);
    }


}
